package com.novanok.papanoeltracking;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.google.android.gms.games.internal.constants.TimeSpan;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.PolygonOptions;

import java.security.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Set;
import java.util.TimeZone;

public class MainActivity extends Activity {

    private static final String TAG = "MainActivity";
    private SimpleDateFormat dt = new SimpleDateFormat("HH:mm:ss.SSS");

    private Marker markerInicio;
    private LatLng[] coords = new LatLng[]{ new LatLng(66.495717, 25.775504), new LatLng(67.007716, 26.578155), new LatLng(66.592241, 27.577911) };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.seleccionarZonaGeografica();
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        String valorHusoHorario = sharedPref.getString("gmt", "");

        Log.i(TAG, "Valor Huso Horario : " + valorHusoHorario );

        HusoHorario hh = new HusoHorario("", "", valorHusoHorario );

        dt.setTimeZone(TimeZone.getTimeZone("UTC"));

        Calendar inicio;
        inicio = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        inicio.set(2014, Calendar.JANUARY, 1, 0, 0, 0);

        Calendar fin;
        fin = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        fin.set(2014, Calendar.DECEMBER, 24, 23, 59, 59);

        Calendar actual;
        actual = Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) );
        long tiempo = ( fin.getTimeInMillis() - actual.getTimeInMillis() );
        long tiempoInicio = tiempo + (-12 * 60 * 60 * 1000);

        double huso = hh.getHora() + ( ( hh.getMinuto() == 30 ) ? 0.5 : 0 );

        Log.i( TAG, "Hora " + hh.getHora() );
        Log.i( TAG, "Minuto " + hh.getMinuto() );
        Log.i( TAG, "Huso Horario " + huso );

        long tiempoLocal = tiempo + (long)( ( 60 * 60 * 1000 ) * ( -1 ) * ( huso ) );

        new CountDownTimerImpl( tiempoInicio ).start();
        new CountDownTimerLocal( tiempoLocal ).start();
    }

    public void onResume(){
        super.onResume();
    }

    @Override
    public boolean onCreateOptionsMenu( Menu menu ) {
        getMenuInflater().inflate( R.menu.main, menu );
        return true;
    }

    @Override
    public boolean onOptionsItemSelected( MenuItem item ) {
        switch ( item.getItemId() ) {
            case R.id.ver_huso_horario:
                Intent i = new Intent( this, HusoHorarioActivity.class );
                startActivity(i);

                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private final class CountDownTimerImpl extends CountDownTimer {
        private static final long TIME_INTERVAL = 100;
        private int i;
        private int j;

        public CountDownTimerImpl( long time ) {
            super(time, TIME_INTERVAL);

            GoogleMap map = (( MapFragment ) getFragmentManager().findFragmentById( R.id.map )).getMap();
            map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(66.495717, 25.775504), 4));

            MarkerOptions op = new MarkerOptions().position(new LatLng(66.495717, 25.775504));
            op.title("Estoy Haciendo los Regalos para Repartir...");
            op.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher));

            markerInicio = map.addMarker(op);
        }

        public void onTick( long millisUntilFinished ) {
            i++;

            if ( i == 10 ){
                markerInicio.setPosition(coords[j]);

                i = 0;
                j++;

                if ( j > 2 )
                    j = 0;
            }

            long totalMilisecodsYear = (long)365 * (long)24 * (long)60 * (long)60 * (long)1000;
            long diferencia = totalMilisecodsYear - millisUntilFinished;
            double cantidadRegalos = ( (double)diferencia / (double)totalMilisecodsYear ) * Double.parseDouble("7000000000");

            int dias = (int)( (float)millisUntilFinished / (float)1000 / (float)60 / (float)60 / (float)24 );
            (( TextView )findViewById( R.id.lblTimeElapsed )).setText(String.valueOf(dias) + ":" + dt.format(new Date(millisUntilFinished)));
            (( TextView )findViewById( R.id.lblCantidadRegalos )).setText("Regalos Fabricados : " + conversion( cantidadRegalos ).replace(",", "."));
        }

        public void onFinish() {
            (( TextView )findViewById( R.id.lblTimeElapsed )).setText("000:00:00:00");

            if ( markerInicio != null )
                markerInicio.remove();

            long tiempo = 86400000;
            new CountDownUbicacion( tiempo ).start();
        }
    }

    private final class CountDownTimerLocal extends CountDownTimer {
        private static final long TIME_INTERVAL = 100;
        private int i;
        private int j;

        public CountDownTimerLocal(long time) {
            super(time, TIME_INTERVAL);
        }

        public void onTick( long millisUntilFinished ) {
            int dias = (int)( (float)millisUntilFinished / (float)1000 / (float)60 / (float)60 / (float)24 );
            (( TextView )findViewById( R.id.lblTimeElapsedLocal )).setText(String.valueOf( dias ) + ":" + dt.format( new Date( millisUntilFinished )));
        }

        public void onFinish() {
            (( TextView )findViewById( R.id.lblTimeElapsedLocal )).setText("000:00:00:00");
            Intent i = new Intent( MainActivity.this, FelizNavidadActivity.class );
            startActivity(i);
        }
    }

    private final class CountDownUbicacion extends CountDownTimer{
        private static final long TIME_INTERVAL = 1000;
        private double latitud = 0;
        private double longitud = 0;
        private Marker mar;
        private GoogleMap map;
        private boolean primeraVez = true;
        private ArrayList<Regalo> listaRegalos;

        public CountDownUbicacion(long time) {
            super(time, TIME_INTERVAL);

            listaRegalos = new ArrayList<Regalo>();

            for ( String anArr : getResources().getStringArray(R.array.coord) ) {
                double lat = Double.parseDouble(anArr.split(";")[0].replace(",", "."));
                double lon = Double.parseDouble(anArr.split(";")[1].replace(",", "."));
                listaRegalos.add(new Regalo(lat, lon, false));
            }

            map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
            map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitud, longitud), 10));
            MarkerOptions op = new MarkerOptions().position(new LatLng(latitud, longitud));
            op.title("Ya llego!!!");
            op.icon(BitmapDescriptorFactory.fromResource(R.drawable.trineo));

            mar = map.addMarker(op);
        }

        @Override
        public void onTick(long l) {
            Calendar actual = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
            actual.set(1900, Calendar.JANUARY, 1);

            Calendar hasta = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
            hasta.set(1900, Calendar.JANUARY, 1, 23, 59, 59);

            Calendar desde = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
            desde.set(1900, Calendar.JANUARY, 1, actual.get(Calendar.HOUR_OF_DAY), actual.get(Calendar.MINUTE), 0);

            Calendar resultado = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
            resultado.set(Calendar.MILLISECOND, (int)(hasta.getTimeInMillis() - desde.getTimeInMillis()));

            long grados;
            if ( actual.get( Calendar.HOUR_OF_DAY ) >= 0 && actual.get( Calendar.HOUR_OF_DAY ) <= 11 )
                grados = (((((( actual.get( Calendar.HOUR_OF_DAY ) * 60 ) + actual.get( Calendar.MINUTE )) * 60) + actual.get( Calendar.SECOND )) * 180) / 43200);
            else
                grados = (((((( ( actual.get( Calendar.HOUR_OF_DAY ) - 12) * 60 ) + actual.get( Calendar.MINUTE )) * 60) + actual.get( Calendar.SECOND )) * 180) / 43200) - 180;

            longitud = (((double)grados + ( actual.get( Calendar.MINUTE ) / (double)60) + ( actual.get( Calendar.SECOND ) / (double)3600) ) * -1 );

            LatLng lat = new LatLng(latitud, longitud);

            if ( mar != null ){
                actualizarRegalos();
                mar.setPosition( lat );

                if ( primeraVez ){
                    map.animateCamera(CameraUpdateFactory.newLatLngZoom(lat, 10));
                    primeraVez = false;
                }
            }
        }

        @Override
        public void onFinish() {

        }

        private void actualizarRegalos(){
            for ( Regalo r : listaRegalos ) {
                if ( r.getLongitud() >= longitud && !r.isEntregado()) {
                    MarkerOptions marOp = new MarkerOptions().position(new LatLng(r.getLatitud(), r.getLongitud()));
                    marOp.title("Regalo !!!");
                    marOp.icon(BitmapDescriptorFactory.fromResource(R.drawable.regalo));
                    Marker m = map.addMarker(marOp);

                    r.setEntregado(true);
                }
            }
        }
    }

    public String conversion(double valor)
    {
        Locale.setDefault(Locale.US);
        DecimalFormat num = new DecimalFormat("#,###,###,###");
        return num.format(valor);
    }

    private void seleccionarZonaGeografica(){
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        String gmt = sharedPref.getString("gmt", "");

        if ( gmt.compareTo("") == 0 ){
            Intent i = new Intent( this, HusoHorarioActivity.class );
            startActivity(i);
        }
    }
}